package br.com.sgc.dao;

import java.util.List;

import javax.ejb.Stateless;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import br.com.sgc.entities.financeiro.PedidoVenda;
import br.com.sgc.enuns.TipoOrdenacao;

@Stateless
public class PedidoVendaDao extends GenericDao<PedidoVenda> {

	private static final long serialVersionUID = 4114844019289693409L;

	public Long findLastIndex() {
		Criteria criteria = getCriteria(PedidoVenda.class);
		criteria.setProjection(Projections.max("indexNumeroPedido"));
		Long index = (Long) criteria.uniqueResult();
		if(index == null) 
			index = 0L;
		
		
		return index;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<PedidoVenda> findAll(PedidoVenda modelClass, Long clinicaId,
			Integer startPage, Integer maxPage, String orderField,
			Boolean initializeDependecies, TipoOrdenacao ordenacao) {
		
		Criteria criteria = getCriteria((Class<PedidoVenda>)modelClass.getClass());
		createCriteriaRestrictions(criteria, modelClass);
		criteria.setFirstResult(startPage);
		criteria.setMaxResults(maxPage);		
		
		if(orderField != null && !orderField.trim().equals(""))
			if(ordenacao.equals(TipoOrdenacao.ASC)){
				criteria.addOrder(Order.asc(orderField));
			} else {
				criteria.addOrder(Order.desc(orderField));
			}
		
		List<PedidoVenda> lista = criteria.list();
		for(PedidoVenda t : lista){
			t.getCliente().toString();
			t.getCliente().getPessoa().toString();
		}
			
		return lista;
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public Long count(PedidoVenda modelClass, Long clinicaId) {
		Long size = 0L;
		Criteria criteria = getCriteria((Class<PedidoVenda>)modelClass.getClass());
		createCriteriaRestrictions(criteria, modelClass);
		criteria.setProjection(Projections.rowCount());
		size = (Long) criteria.uniqueResult();
        return size;
	}


	private void createCriteriaRestrictions(Criteria criteria, PedidoVenda modelClass) {
		if(modelClass != null){
			if(modelClass.getClinica() != null && modelClass.getClinica().getId() != null){
				criteria.add(Restrictions.eq("clinica.id", modelClass.getClinica().getId()));
			}
			
			if(modelClass.getCancelado()!= null && modelClass.getCancelado()){
				criteria.add(Restrictions.eq("cancelado", modelClass.getCancelado()));
			}
			if(modelClass.getFinalizado()!= null && modelClass.getFinalizado()){
				criteria.add(Restrictions.eq("finalizado", modelClass.getFinalizado()));
			}
			if(modelClass.getGuardado() != null && modelClass.getGuardado()){
				criteria.add(Restrictions.eq("guardado", modelClass.getGuardado()));
			}
		}
		
	}
	
	

}
